package com.snowyee.snowyeecodesandbox.service.impl;

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.util.ArrayUtil;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import com.snowyee.snowyeecodesandbox.model.ExecuteCodeRequest;
import com.snowyee.snowyeecodesandbox.model.ExecuteCodeResponse;
import com.snowyee.snowyeecodesandbox.model.ExecuteMessage;
import com.snowyee.snowyeecodesandbox.service.CodeSandbox;
import com.snowyee.snowyeecodesandbox.service.JavaCodeSandboxTemplate;
import org.springframework.stereotype.Service;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class DockerCodeSandboxImpl extends JavaCodeSandboxTemplate implements CodeSandbox{

    private static final Boolean FIRST_INIT = false;

    private static final Long TIME_OUT = 5000L;

    @Override
    public List<ExecuteMessage> runCode(List<String> inputList) {
        // 3、创建容器，把文件复制到容器内，同时搜集时间和内存占用等信息
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();
        String images = "openjdk:8-alpine";
        if (FIRST_INIT){
            PullImageCmd pullImageCmd = dockerClient.pullImageCmd(images);
            PullImageResultCallback pullImageResultCallback = new PullImageResultCallback(){
                @Override
                public void onNext(PullResponseItem item){
                    System.out.println("下载镜像：" + item.getStatus());
                    super.onNext(item);
                }
            };
            try {
                pullImageCmd
                        .exec(pullImageResultCallback)
                        .awaitCompletion();
            } catch (InterruptedException e) {
                System.out.println("拉取镜像异常");
                throw new RuntimeException(e);
            }
            System.out.println("下载完成");
        }

        // 创建容器
        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(images);
        // 限制容器的配置
        HostConfig hostConfig = new HostConfig();
        // 限制内存最大只能使用100M
        hostConfig.withMemory(100*100*1000L);
        // 限制不让把信息从内存写到硬盘
        hostConfig.withMemorySwap(0L);
        // 限制CPU最多使用1核
        hostConfig.withCpuCount(1L);
        // 具体限制一个一个的权限
//        hostConfig.withSecurityOpts(Arrays.asList("seccomp=安全管理配置的字符串"));
        // 把数据挂载到/app目录下
        hostConfig.setBinds(new Bind(super.userCodeParentPath,new Volume("/app")));
        CreateContainerResponse createContainerResponse = containerCmd
                .withHostConfig(hostConfig)
                // 限制不让使用网络
                .withNetworkDisabled(true)
                // 限制根目录只读，不可写
                .withReadonlyRootfs(true)
                .withAttachStderr(true)
                .withAttachStdin(true)
                .withAttachStdout(true)
                .withTty(true)
                .exec();
        System.out.println(createContainerResponse);
        String containerId = createContainerResponse.getId();

        // 4、启动容器，执行代码
        dockerClient.startContainerCmd(containerId).exec();

        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String inputArgs :inputList){
            StopWatch stopWatch = new StopWatch();
            String[] inputArgsArray = inputArgs.split(" ");
            // docker exec eloquent_goodall java -cp /app Main 1 3
            String[] cmdArray = ArrayUtil.append(new String[]{"java", "-cp", "/app", "Main"}, inputArgsArray);
            ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(containerId)
                    .withCmd(cmdArray)
                    .withAttachStderr(true)
                    .withAttachStdin(true)
                    .withAttachStdout(true)
                    .exec();
            System.out.println("创建执行命令" + execCreateCmdResponse);

            ExecuteMessage executeMessage = new ExecuteMessage();
            final String[] message = {null};
            final String[] errormessage = {null};
            long time = 0L;
            // 判断是否超时
            final boolean[] timeout = {true};
            String execId = execCreateCmdResponse.getId();
            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback(){

                @Override
                public void onNext(Frame frame){
                    StreamType streamType = frame.getStreamType();
                    if (StreamType.STDERR.equals(streamType)){
                        errormessage[0] = new String(frame.getPayload());
                        System.out.println("输出错误结果：" + errormessage[0]);
                    } else {
                        message[0] = new String(frame.getPayload());
                        System.out.println("输出结果：" + message[0]);
                    }
                    super.onNext(frame);
                }

                // 程序结束时执行这个
                @Override
                public void onComplete() {
                    timeout[0] = false;
                    super.onComplete();
                }
            };

            final long[] maxMemory = {0L};
            // 获取占用内存信息
            StatsCmd statsCmd = dockerClient.statsCmd(containerId);
            statsCmd.exec(new ResultCallback<Statistics>() {
                @Override
                public void onComplete(){

                }

                @Override
                public void onStart(Closeable closeable) {

                }

                @Override
                public void onNext(Statistics statistics) {
                    System.out.println("内存占用" + statistics.getMemoryStats().getUsage());
                    maxMemory[0] = Math.max(statistics.getMemoryStats().getUsage(), maxMemory[0]);
                }

                @Override
                public void onError(Throwable throwable) {

                }


                @Override
                public void close() throws IOException {

                }
            });

            try {
                stopWatch.start();
                dockerClient.execStartCmd(execId)
                        .exec(execStartResultCallback)
                        // 控制程序是否超时
                        // TIME_OUT, TimeUnit.MICROSECONDS
                        .awaitCompletion();
                stopWatch.stop();
                time = stopWatch.getLastTaskTimeMillis();
                statsCmd.close();
            } catch (InterruptedException e) {
                System.out.println("程序执行异常");
                throw new RuntimeException(e);
            }

            executeMessage.setErrorMessage(errormessage[0]);
            executeMessage.setMessage(message[0]);
            executeMessage.setTime(time);
            executeMessage.setMemory(maxMemory[0]);
            executeMessageList.add(executeMessage);
        }

        return executeMessageList;
    }

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        return super.executeCode(executeCodeRequest);
    }
}
